package com.jack.thinking.thread.core._5;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class ScheduleAtFixedRateNoDelay {
	private static Timer timer = new Timer(false);
	private static Timer timer2 = new Timer(false);
	private static int runCount = 0;
	private static int runCount2 = 0;
	
	static public class MyTask1 extends TimerTask{
		
		@Override
		public void run() {
			System.out.println("1 begin , time is " + new Date());
			if(runCount % 2 ==0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}else {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.out.println("1   end , time is " + new Date());
			runCount++;
			if(runCount == 10) {
				this.cancel();
			}
		}
		
	}
	
	static public class MyTask2 extends TimerTask{
		
		@Override
		public void run() {
			System.out.println("2 begin , time is " + new Date());
			if(runCount2 % 2 == 0) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}else {
				try {
					Thread.sleep(10000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.out.println("2   end , time is " + new Date());
			runCount2++;
			if(runCount2 == 10) {
				this.cancel();
			}
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		MyTask1 task1 = new MyTask1();
		MyTask2 task2 = new MyTask2();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = "2019-01-06 18:12:00";
		Date dateRef = sdf.parse(dateString);
		System.out.println("target time:" + dateRef + " system time:" + new Date());
		timer.schedule(task1, dateRef, 2000);
		timer2.scheduleAtFixedRate(task2, dateRef, 2000);
	}
}
